package su.mvc.service.gui;


import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.googlecode.objectify.Key;
import org.apache.commons.io.IOUtils;
import su.mvc.model.Image;
import su.mvc.service.DaoSupport;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

public class ImageService extends DaoSupport {
    
    public static final String BYTES_ENCODING = "ISO-8859-1";
    
    public static final Integer ICON_SIZE = 150;

    private static final Logger log = Logger.getLogger(ImageService.class.getName());
    
    public void saveImages(List<String> imageBytes, List<String> imageFileNames, List<String> imageContentTypes, Key parentKey) throws IOException{
        for (int i = 0; i < imageBytes.size(); i++) {
            Image image = new Image();
            byte[] imgBytes = IOUtils.toByteArray(IOUtils.toInputStream(imageBytes.get(i), BYTES_ENCODING));
            image.setImage(imgBytes);
            image.setName(imageFileNames.get(i));
            image.setContentType(imageContentTypes.get(i));
            image.setParentItemKey(parentKey);
            image.setIcon(getIconFromImage(imgBytes));
            getObjectify().put(image);
        }
    }
    
    public List<Image> getImagesByMenuItem(Key menuItemKey) throws  Exception{
        return getObjectify().query(Image.class).filter("parentItemKey", menuItemKey).list();
    }
    
    public Image getImageById(Long id) {
        return getObjectify().get(Image.class, id);
    }
    
    public void deleteImage(Long id) {
        getObjectify().delete(getImageById(id));
    }
    
    public byte[] getIconFromImage(byte[] image) {
        ImagesService imagesService = ImagesServiceFactory.getImagesService();
        com.google.appengine.api.images.Image srcImage = ImagesServiceFactory.makeImage(image);
        Transform resize = ImagesServiceFactory.makeResize(ICON_SIZE, ICON_SIZE);
        Transform ifl = ImagesServiceFactory.makeImFeelingLucky();
        com.google.appengine.api.images.Image icon = imagesService.applyTransform(resize, srcImage);
        icon = imagesService.applyTransform(ifl, icon);
        return icon.getImageData();
    }
    
}
